package com.gxa.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//获取验证码
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取specCaptcha核心对象
        SpecCaptcha specCaptcha = new SpecCaptcha(120,40,4);
//        获取验证码的值
        String verCode = specCaptcha.text();
//        存储code在服务器session中
        request.getSession().setAttribute("serverCode", verCode);
//        生成图片验证码后，用流传递给前端
        Map map = new HashMap();
        map.put("image", specCaptcha.toBase64());
//        设置响应编码
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONObject.toJSONString(map));
    }
}
